<?php
namespace api\modules\v1\models\userReceipt;

use api\modules\v1\models\user\User;
use api\modules\v1\models\user\UserKyc;
use common\models\Functions;
use common\models\Patterns;
use common\models\Status;
use common\services\auth\AuthApiAliyun;
use common\vendor\AuthApi;
use yii\base\Exception;
use Yii;
/**
 * Class EmployeeInfo
 * @package api\modules\v1\models\employee
 */
class ReceiptBank extends \common\models\userReceipt\ReceiptBank
{
    public function bind() {
        try {
            $user = (new User())->checkUser();
            // 检查用户信息
            (new \common\models\user\User()) -> checkInfo($user);

            $post = \Yii::$app->request->post();

            $cardNo = $post['card_no'];
            $bankName = strip_tags($post['bank_name']);
            $bankHolder = strip_tags($post['bank_holder']);

            if (empty($cardNo) || empty($bankName) || empty($bankHolder)) {
                throw new Exception('参数错误');
            }

            # 检查银行卡格式
            if (!preg_match(Patterns::bankCardNo(), $cardNo)) {
                throw new Exception('银行卡格式不正确');
            }

            // 检查是否被绑定
//            $info = static::getOneByWhere(['card_no' => $cardNo,'is_delete' => Status::COMMON_IS_NOT_DELETE]);
//            if (!empty($info) && $info['user_id'] != $user['id']) {
//                throw new Exception("该银行卡已被绑定，请更换其他银行卡");
//            }

            $count = static::getCountByWhere(['user_id' => $user['id'],'is_delete' => Status::COMMON_IS_NOT_DELETE]);
            if ($count > 5) {
                throw new Exception("最多绑定5张银行卡");
            }
//
//            if (empty($post['card_photo'])) {
//                throw new Exception("请上传银行卡照片");
//            }
//

            $userKyc = UserKyc::getOneByWhere(['user_id' => $user['id']]);
            if (!empty($userKyc) && $userKyc['true_name'] != $bankHolder) {
                throw new Exception("持卡人姓名和实名认证不符合");
            }

//            $checkWhere['user_id'] = $user['id'];
//            $check = static::getOneByWhere($checkWhere);

            #银行卡三要素验证
            $res = (new AuthApiAliyun())->authBank($userKyc['true_name'], $userKyc['id_card'], $cardNo);
            if (empty($res) || $res['code'] !== 200) {
                throw new Exception('系统繁忙，请稍后再试');
            }
            if ($res['data']['result'] != 0) {
                throw new Exception('银行卡绑定失败，请使用您本人的银行卡');
            }

            $data['card_no'] = $cardNo;
            $data['bank_name'] = $bankName;
            $data['bank_holder'] = $bankHolder;
            $data['card_photo'] = strip_tags($post['card_photo']);
            $data['user_id'] = $user['id'];
            $data['create_time'] = date("Y-m-d H:i:s");
            $res = static::insertData($data);
            if ($res === false) {
                throw new Exception('绑定失败');
            }

            return Functions::formatRestAPI(0, '设置成功。');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    public function getInfo() {
        try {
            $user = (new User())->checkUser();

            $where['user_id'] = $user['id'];
            $data = static::getOneByWhere(['user_id' => $user['id']], ['card_no', "bank_name", "bank_holder"]);

            if (!empty($data)) {
                //            $data['card_no'] = (string) $data['card_no'];
//            $data['bank_name'] = (string) $data['bank_name'];
//            $data['bank_holder'] = (string) $data['bank_holder'];

                $data['card_photo_path'] = $data['card_photo'];
                $data['card_photo'] = empty($data['card_photo']) ? "" : static::getImages($data['card_photo']);
            }

            $data['ps'] = "1：务必确定卡号与上传图片一致。\n2：务必确定上传卡号与实际填写持卡人一致。";

            return Functions::formatRestAPI(0, '', $data);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    // 解绑银行卡
    public function unBind($id = 0) {
        try {
            $user = (new User())->checkUser();

            if ($user['is_kyc'] == Status::COMMON_RADIO_NO) {
                throw new Exception('未实名，请完成实名认证');
            }

            $id = $id ? $id : Yii::$app->request->post('id',0);
            if (empty($id)) {
                throw new Exception('参数错误');
            }

            // 检查是否被绑定
            $info = static::getOneByWhere(['id' => $id,'is_delete' => Status::COMMON_IS_NOT_DELETE]);
            if (!empty($info) && $info['user_id'] != $user['id']) {
                throw new Exception("未知银行卡信息");
            }

            $data['is_delete'] = Status::COMMON_IS_DELETE;
            $data['delete_time'] = date("Y-m-d H:i:s");
            $res = static::updateData($data,['id' => $id]);
            if ($res === false) {
                throw new Exception('解绑失败');
            }
            return Functions::formatRestAPI(0, '解绑成功。');
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

    /**
     * 银行卡列表
     * @return array
     */
    public function getList()
    {
        try{
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $where = $andWhere = [];
            $where['user_id'] = $user['id'];
            $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'id DESC')->with([
            ])->asArray()->all();
            $result = [];
            foreach ($list as $v) {
                $result[] = [
                    'id' => (int) $v['id'],
                    'bank_name' => $v['bank_name'] ?: '',
                    'bank_holder' => Functions::replaceStartFilter($v['bank_holder'], 1, 0),
                    'card_no' => Functions::hiddenPhone($v['card_no'], 1, strlen($v['card_no']) - 2 ),
                ];
            }

            return Functions::formatRestAPI(0, '', $result);
        } catch (\yii\db\Exception $ee) {
            return Functions::formatRestAPI(1, '服务异常');
        } catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }
}
